package admin

import (
	"github.com/gin-gonic/gin"
	"github.com/shopspring/decimal"
	"mojieshi/define"
	"mojieshi/models"
	"net/http"
	"strconv"
	"time"
)

type businessJson struct {
	ID     int    `json:"id"`
	Aid    int    `json:"aid"`     //商户id
	Cid    string `json:"cid"`     //分类id
	Name   string `json:"name"`    //
	Status int    `json:"status"`  //状态 0待审核 1已通过 2已驳回 -1已过期
	IsOpen int    `json:"is_open"` //营业状态
	Page   int    `json:"page"`
	Limit  int    `json:"limit"`
}
type businessDate struct {
	ID         int             `gorm:"type:int(11); primaryKey" json:"id"`
	Aid        int             `gorm:"type:int(11);" json:"aid"` //商户id
	Mid        int             `gorm:"type:int(11);" json:"mid"` //
	Cid        string          `json:"cid"`                      //分类id
	Name       string          `json:"name"`                     //
	Logo       string          `json:"logo"`                     //
	Desc       string          `json:"desc"`                     //
	Linkman    string          `json:"linkman"`                  //
	Linktel    string          `json:"linktel"`                  //
	Pics       string          `json:"pics"`                     //
	Content    string          `json:"content"`                  //
	Province   string          `json:"province"`                 //
	City       string          `json:"city"`                     //
	District   string          `json:"district"`                 //
	Address    string          `json:"address"`                  //
	Money      decimal.Decimal `json:"money"`                    //
	Sales      int             `json:"sales"`                    //
	Viewnum    int             `json:"viewnum"`                  //
	Feepercent float64         `json:"feepercent"`               //费率
	Sort       int             `json:"sort"`                     //
	Kfurl      string          `json:"kfurl"`                    //
	Createtime int             `json:"createtime"`               //
	Endtime    int             `json:"endtime"`                  //
	Status     int             `json:"status"`                   //状态 0待审核 1已通过 2已驳回 -1已过期
	IsOpen     int             `json:"is_open"`                  //营业状态
	CName      string          `json:"c_name"`                   //名称
}

// 获取列表
func BusinessList(c *gin.Context) {
	var jsonData businessJson
	err := c.ShouldBindJSON(&jsonData)
	if err != nil {
		define.Response.ResultFail(c, 10000, define.JsonData, "")
		return
	}
	var list []businessDate
	var count int64
	if jsonData.Page == 0 {
		jsonData.Page = -1
	}
	if jsonData.Limit == 0 {
		jsonData.Limit = -1
	}
	offsetVal := (jsonData.Page - 1) * jsonData.Limit
	if jsonData.Page == -1 && jsonData.Limit == -1 {
		offsetVal = -1
	}
	selectData := "m_business.id,m_business.aid,m_business.cid,m_business.mid,m_business.name,m_business.logo,m_business.desc,m_business.linkman,m_business.linktel" +
		",m_business.pics,m_business.content,m_business.province,m_business.city,m_business.district,m_business.address,m_business.money,m_business.sales" +
		",m_business.viewnum,m_business.feepercent,m_business.sort,m_business.kfurl,m_business.createtime,m_business.endtime,m_business.status,m_business.is_open,m_business_category.name as c_name"
	tx := models.DB.Table("m_business").Select(selectData).Joins("left join m_business_category on m_business_category.id=m_business.cid").Where("m_business.aid=? AND m_business.name LIKE ?", jsonData.Aid, "%"+jsonData.Name+"%")
	if jsonData.IsOpen > 0 {
		tx = tx.Where("m_business.is_open=?", jsonData.IsOpen)
	}
	if jsonData.Status > -2 {
		tx = tx.Where("m_business.status=?", jsonData.Status)
	}
	if jsonData.Cid != "" {
		tx = tx.Where("m_business.cid=?", jsonData.Cid)
	}
	tx = tx.Count(&count).Limit(jsonData.Limit).Offset(offsetVal).Order("id desc").Find(&list)
	if tx.Error != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10001,
			"msg":  tx.Error,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"code":    0,
		"data": map[string]interface{}{
			"list":  list,
			"count": count,
		},
	})
}

// 新增or修改
func BusinessAdd(c *gin.Context) {
	//获取传值
	var jsonData models.MBusiness
	err := c.ShouldBindJSON(&jsonData)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  err,
		})
		return
	}
	tx := models.DB.Begin() //开启事务
	if jsonData.ID > 0 {
		//修改数据
		var editData = map[string]interface{}{
			"name":       jsonData.Name,
			"cid":        jsonData.Cid,
			"logo":       jsonData.Logo,
			"desc":       jsonData.Desc,
			"linkman":    jsonData.Linkman,
			"linktel":    jsonData.Linktel,
			"pics":       jsonData.Pics,
			"kfurl":      jsonData.Kfurl,
			"content":    jsonData.Content,
			"province":   jsonData.Province,
			"city":       jsonData.City,
			"district":   jsonData.District,
			"address":    jsonData.Address,
			"endtime":    jsonData.Endtime / 1000,
			"feepercent": jsonData.Feepercent,
			"status":     jsonData.Status,
			"is_open":    jsonData.IsOpen,
		}
		err = tx.Model(new(models.MBusiness)).Where("id=?", jsonData.ID).Updates(&editData).Error
		if err != nil {
			c.JSON(http.StatusOK, gin.H{
				"code": 10002,
				"msg":  err.Error(),
			})
			tx.Rollback()
			return
		}
		//写入日志
		userId, _ := strconv.Atoi(c.GetHeader("userId")) //将字符串转为int
		userName, bid := models.UserName(userId)
		logData := "管理员：" + userName + "，修改了商户:" + strconv.Itoa(jsonData.ID) + "的内容"
		models.LogAdd(3, "修改商户", userId, logData, bid, jsonData.Aid)
	} else {
		var data models.MBusiness
		data.Cid = jsonData.Cid
		data.Aid = jsonData.Aid
		data.Name = jsonData.Name
		data.Logo = jsonData.Logo
		data.Desc = jsonData.Desc
		data.Linkman = jsonData.Linkman
		data.Linktel = jsonData.Linktel
		data.Tel = jsonData.Linktel
		data.Pics = jsonData.Pics
		data.Feepercent = jsonData.Feepercent
		data.Content = jsonData.Content
		data.Province = jsonData.Province
		data.City = jsonData.City
		data.District = jsonData.District
		data.Address = jsonData.Address
		data.Longitude = "116.39782905578613"
		data.Latitude = "39.90358020251377"
		data.Createtime = int(time.Now().Unix())
		data.Endtime = jsonData.Endtime / 1000
		data.Status = jsonData.Status
		data.Money = decimal.NewFromInt(0)
		data.CommentScore = decimal.NewFromInt(5)
		data.CommentNum = 0
		data.CommentHaopercent = 100
		data.Kfurl = jsonData.Kfurl
		data.StartHours = "00:00"
		data.EndHours = "00:00"
		data.Invoice = 0
		data.InvoiceType = "1"
		data.IsOpen = 1
		data.Autocollecthour = 168
		data.StartHours2 = "00:00"
		data.EndHours2 = "00:00"
		data.StartHours3 = "00:00"
		data.EndHours3 = "00:00"
		data.EndBuyStatus = 0
		data.Wxpayst = 0
		data.BusinessSelfscoreMinus = -1
		data.Scoreset = 0
		data.Score2money = "0.01"
		data.Scoredkmaxpercent = decimal.NewFromInt(100.00)
		data.Scorebdkyf = 0
		data.Couponmoney = decimal.NewFromInt(0)
		data.File_ImageTotal = 0
		data.FileOtherTotal = 0
		data.FileUploadTotal = 0
		data.FileVideoTotal = 0
		err = tx.Model(new(models.MBusiness)).Create(&data).Error
		if err != nil {
			c.JSON(http.StatusOK, gin.H{
				"code": 10001,
				"msg":  err.Error(),
			})
			tx.Rollback()
			return
		}
		var userdata models.MAdminUser
		var count int64
		err = models.DB.Model(new(models.MAdminUser)).Where("phone=?", jsonData.Linktel).Count(&count).Find(&userdata).Error
		if err != nil {
			c.JSON(http.StatusOK, gin.H{
				"code": 10006,
				"msg":  err.Error(),
			})
			tx.Rollback()
			return
		}
		if count > 0 {
			c.JSON(http.StatusOK, gin.H{
				"code": 10002,
				"msg":  "手机号已被使用",
			})
			tx.Rollback()
			return
		}
		//写入日志
		userId, _ := strconv.Atoi(c.GetHeader("userId")) //将字符串转为int
		userName, bid := models.UserName(userId)
		logData := "管理员：" + userName + "，新增了一个商户:" + jsonData.Name
		models.LogAdd(2, "新增商户", userId, logData, bid, jsonData.Aid)
		//写入管理员表
		var addData models.MAdminUser
		addData.Bid = data.ID
		addData.UserName = jsonData.Linkman
		addData.UserPic = jsonData.Logo
		addData.OperatorUid = userId
		addData.Phone = jsonData.Linktel
		addData.Password = define.GetMD5(jsonData.Bankname)
		addData.GroupId = 3
		addData.Status = 1
		addData.IsShow = 1
		addData.Language = "zh"
		err = tx.Model(new(models.MAdminUser)).Create(&addData).Error
		if err != nil {
			c.JSON(http.StatusOK, gin.H{
				"code": 10004,
				"msg":  err.Error(),
			})
			tx.Rollback()
			return
		}
		var editData = map[string]interface{}{
			"mid": addData.ID,
		}
		err = tx.Model(new(models.MBusiness)).Where("id=?", data.ID).Updates(&editData).Error
		if err != nil {
			c.JSON(http.StatusOK, gin.H{
				"code": 10005,
				"msg":  err.Error(),
			})
			tx.Rollback()
			return
		}
	}
	tx.Commit()
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"code":    0,
		"msg":     "成功！",
	})
}

// 暂停营业
func BusinessStop(c *gin.Context) {
	var jsonData models.MBusiness
	err := c.ShouldBindJSON(&jsonData)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  err,
		})
		return
	}
	var editData = map[string]interface{}{
		"is_open": jsonData.IsOpen,
	}
	err = models.DB.Model(new(models.MBusiness)).Where("id=?", jsonData.ID).Updates(&editData).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10005,
			"msg":  err.Error(),
		})
		return
	}
	//写入日志
	userId, _ := strconv.Atoi(c.GetHeader("userId")) //将字符串转为int
	userName, bid := models.UserName(userId)
	logData := "管理员：" + userName + "，修改了商户:" + jsonData.Name + "，的营业状态"
	models.LogAdd(9, "修改商户营业", userId, logData, bid, jsonData.Aid)
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"code":    0,
		"msg":     "成功！",
	})
}

// 删除商户
func BusinessDel(c *gin.Context) {
	var jsonData models.MBusiness
	err := c.ShouldBindJSON(&jsonData)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  err,
		})
		return
	}
	var data models.MBusiness
	models.DB.Model(new(models.MBusiness)).Where("id=?", jsonData.ID).First(&data)

	tx := models.DB.Begin()
	//删除
	err = tx.Delete(&models.MBusiness{}, jsonData.ID).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10004,
			"msg":  err.Error(),
		})
		tx.Rollback()
		return
	}
	err = tx.Delete(&models.MAdminUser{}, "bid=?", data.ID).Error
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10005,
			"msg":  err.Error(),
		})
		tx.Rollback()
		return
	}
	tx.Commit()
	//写入日志
	userId, _ := strconv.Atoi(c.GetHeader("userId")) //将字符串转为int
	userName, bid := models.UserName(userId)
	logData := "管理员：" + userName + "，删除了一个商户:" + data.Name
	models.LogAdd(4, "删除商户", userId, logData, bid, jsonData.Aid)
	c.JSON(http.StatusOK, gin.H{
		"success": true,
		"code":    0,
		"msg":     "成功！",
	})
}
